package sysmodels

import (
	"errors"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"strings"
	"time"
)

type SysUser struct {
	Id         int       `orm:"" form:"id" json:"id" `
	Username   string    `orm:"size(30);unique" form:"username" json:"username" ` //账号 唯一
	Name       string    `orm:"size(30)" form:"name" json:"name" json:"name"`     //中文名
	Password   string    `orm:"" json:"-" form:"password"`
	Avatar     string    `orm:"size(100)" form:"avatar" json:"avatar"` //头像
	Sex        string    `orm:"size(10);" form:"sex" description:"male 男 female 女 '' 未知" json:"sex"`
	Phone      string    `orm:"size(11);index" json:"phone" form:"phone" valid:"Mobile"`
	Email      string    `orm:"size(50)" form:"email" json:"email" valid:"Email; MaxSize(100)"`
	Idcard     string    `orm:"size(18);index" form:"idcard" json:"idcard"`
	Birthday   time.Time `orm:"null;type(date)" form:"birthday" json:"birthday"`
	Address     string 	  `orm:"type(text)" form:"address" json:"address"`
	Status     bool      `orm:"default(1)" form:"status" json:"status"`
	CreateTime time.Time `orm:"auto_now_add;type(datetime)" json:"createtime"`
	UpdateTime time.Time `orm:"auto_now;type(datetime)" json:"updatetime"`
	RoleName   string    `orm:"size(50);null" form:"rolename" json:"rolename"` // 角色唯一名称 一个用户一个角色
}

func NewSysUser() *SysUser {
	return &SysUser{
		Status: true,
	}
}

//控制台创建用户
func (this *SysUser) Add() error {
	o := orm.NewOrm()
	if this.Username == "" {
		return errors.New("账号不能为空")
	}
	if o.QueryTable(USERTABLE).Filter("Username", this.Username).Exist() {
		return errors.New("该账号已被注册!")
	}

	if this.Phone != "" && o.QueryTable(USERTABLE).Filter("phone", this.Phone).Exist() {
		return errors.New("该手机号已被注册!")
	}
	//
	if len(this.Idcard) != 18 {
		return errors.New("身份证号格式错误")
	}
	if this.Idcard != "" && o.QueryTable(USERTABLE).Filter("Idcard", this.Username).Exist() {
		return errors.New("该身份证已被注册!")
	}

	if this.RoleName != "" && !o.QueryTable(ROLETABLE).Filter("RoleName", this.RoleName).Exist() {
		return errors.New(strings.Join([]string{this.RoleName, "角色不存在"}, ""))
	}

	if this.Sex != "male" && this.Sex != "female" && this.Sex != "" {
		return errors.New("sex参数必须是 male female")
	}
	this.Password = GetPassword(this.Username + "123")
	_, err := o.Insert(this)
	if err != nil {
		logs.Error(err.Error())
		return errors.New("创建用户失败!")
	}
	return nil
}

//批量查询
func (this *SysUser) Query(limit, page int) ([]*SysUser, int64) {
	qs := orm.NewOrm().QueryTable(USERTABLE)
	var users []*SysUser
	if this.Username != "" {
		qs = qs.Filter("Username__icontains", this.Username)
	}
	if this.Name != "" {
		qs = qs.Filter("Name__icontains", this.Name)
	}
	if this.Idcard != "" {
		qs = qs.Filter("Idcard__icontains", this.Idcard)
	}
	if this.Phone != "" {
		qs = qs.Filter("Phone__icontains", this.Phone)
	}
	if this.Sex != "" {
		qs = qs.Filter("Sex", this.Sex)
	}

	cnt, err := qs.Limit(limit, (page-1)*limit).OrderBy("id").All(&users)
	if err != nil {
		logs.Error("用户数据查询失败:", err)
		return nil, 0
	}
	return users, cnt
}

func (this *SysUser) GetById() error {
	o := orm.NewOrm()
	err := o.Read(this, "Id")
	if !this.Status {
		this = nil
		return orm.ErrNoRows
	}
	return err
}

//更新用户
//func (this *SysUser) UpdateById() error {
//	o := orm.NewOrm()
//	if this.RoleName != "" && !o.QueryTable(ROLETABLE).Filter("RoleName", this.RoleName).Exist() {
//		return errors.New(strings.Join([]string{this.RoleName, "角色不存在"}, ""))
//	}
//	//前端不会获取到密码数据 前端有密码数据提交只能是修改状态
//	if this.Password!=""{
//		this.Password = GetPassword(this.Password)
//	}
//	_, err := o.Update(this)
//	return err
//}

//更新指定字段
func (this *SysUser) Update(cols []string) error {
	o := orm.NewOrm()
	for _, v := range cols {
		if v == "rolename" &&
			!o.QueryTable(ROLETABLE).Filter("RoleName", this.RoleName).Exist() {
			return errors.New(strings.Join([]string{this.RoleName, "角色不存在"}, ""))
		}
		//更新密码
		if v== "password" {
			if this.Password == ""{
				return errors.New("密码不能为空")
			}
			this.Password = GetPassword(this.Password)
		}
	}
	_, err := o.Update(this, cols...)
	return err
}

/*
初始化用户密码
 */
func (this *SysUser) RestPassword() error {
	o := orm.NewOrm()
	err := o.Read(this, "Id")
	if err != nil {
		return err
	}
	this.Password = GetPassword(this.Username + "123")
	_, err = o.Update(this, "Password")
	return err
}

//验证密码
func (this *SysUser) CheckPassword() (bool, error) {
	o := orm.NewOrm()
	password:=this.Password
	err:=o.QueryTable(USERTABLE).Filter("Username", this.Username).Filter("Status", true).One(this)
	if err!=nil{
		return false, errors.New("该账号不存在")
	}

	if this.Password == GetPassword(password) {
		this.Password = ""
		return true, nil
	} else {
		return false, errors.New("密码错误")
	}
}

func (this *SysUser) DeleteById() (int64, error) {
	o := orm.NewOrm()
	row, err := o.Delete(this, "id")
	return row, err
}
